package com.ssy.lingxi.platform.manage.serviceimpl.content;

import cn.hutool.core.collection.CollectionUtil;
import com.querydsl.jpa.impl.JPAQuery;
import com.querydsl.jpa.impl.JPAQueryFactory;
import com.ssy.lingxi.common.constant.basic.EnableDisableStatus;
import com.ssy.lingxi.common.exception.BusinessException;
import com.ssy.lingxi.common.model.dto.UserLoginCacheDTO;
import com.ssy.lingxi.common.response.PageData;
import com.ssy.lingxi.common.response.ResponseCode;
import com.ssy.lingxi.common.response.Wrapper;
import com.ssy.lingxi.platform.manage.constant.CommonBooleanEnum;
import com.ssy.lingxi.platform.manage.entity.content.ContentImage;
import com.ssy.lingxi.platform.manage.entity.content.QContentImage;
import com.ssy.lingxi.platform.manage.model.request.common.CommonIdRequest;
import com.ssy.lingxi.platform.manage.model.request.common.CommonStatusRequest;
import com.ssy.lingxi.platform.manage.model.request.content.ContentImagePageRequest;
import com.ssy.lingxi.platform.manage.model.request.content.ContentImageRequest;
import com.ssy.lingxi.platform.manage.model.response.StartAndGuideResponse;
import com.ssy.lingxi.platform.manage.repository.ContentImageRepository;
import com.ssy.lingxi.platform.manage.service.content.IContentImageService;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 图片管理 - 业务实现层
 *
 * @author fhj
 * @version 2.0.0
 * @date 2020/9/21
 */
@Slf4j
@Service
public class ContentImageServiceImpl implements IContentImageService {

    @Resource
    private ContentImageRepository contentImageRepository;
    @Resource
    private JPAQueryFactory jpaQueryFactory;

    /**
     * 列表
     * @param request 请求实体
     * @return 操作结果
     */
    @Override
    public Wrapper<PageData<ContentImage>> page(ContentImagePageRequest request) {
        QContentImage qContentImage = QContentImage.contentImage;
        JPAQuery<ContentImage> jpaQuery = jpaQueryFactory.select(qContentImage).from(qContentImage);
        if (StringUtils.isNotBlank(request.getName())) {
            jpaQuery.where(qContentImage.name.contains(request.getName()));
        }
        long totalCount = jpaQuery.fetchCount();
        List<ContentImage> list = jpaQuery.orderBy(qContentImage.createTime.desc()).limit(request.getPageSize()).offset((long) (request.getCurrent() - 1) * request.getPageSize()).fetch();
        return Wrapper.success(new PageData<>(totalCount, list));
    }

    /**
     * 详情
     * @param request 请求实体
     * @return 操作结果
     */
    @Override
    public Wrapper<ContentImage> get(CommonIdRequest request) {
        ContentImage contentImage = contentImageRepository.findById(request.getId()).orElse(null);
        if (contentImage == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        return Wrapper.success(contentImage);
    }

    /**
     * 新增
     * @param request 请求实体
     * @param user 当前登录用户
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> add(ContentImageRequest request, UserLoginCacheDTO user) {
        if (request.getSort() != null && contentImageRepository.existsBySort(request.getSort())) {
            return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
        }

        ContentImage contentImage = new ContentImage();
        BeanUtils.copyProperties(request, contentImage);
        contentImageRepository.saveAndFlush(contentImage);
        return Wrapper.success();
    }

    /**
     * 修改
     * @param request 请求实体
     * @param user 当前登录用户
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> update(ContentImageRequest request, UserLoginCacheDTO user) {
        if (request.getSort() != null) {
            ContentImage existsContentImage = contentImageRepository.findBySort(request.getSort());
            if (existsContentImage != null && existsContentImage.getId() - request.getId() != 0) {
                return Wrapper.fail(ResponseCode.PLATFORM_MANAGE_SORT_CANNOT_BE_REPEATED);
            }
        }

        ContentImage contentImage = contentImageRepository.findById(request.getId()).orElse(null);
        if (contentImage == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (contentImage.getStatus().equals(EnableDisableStatus.ENABLE.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        BeanUtils.copyProperties(request, contentImage);
        contentImageRepository.saveAndFlush(contentImage);
        return Wrapper.success();
    }

    /**
     * 停用/启用
     * @param request 请求实体
     * @param user 当前登录用户
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> updateStatus(CommonStatusRequest request, UserLoginCacheDTO user) {
        ContentImage contentImage = contentImageRepository.findById(request.getId()).orElse(null);
        if (contentImage == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        contentImage.setStatus(request.getEnableStatus());
        contentImageRepository.saveAndFlush(contentImage);
        return Wrapper.success();
    }

    /**
     * 删除
     * @param request 请求实体
     * @param user 当前登录用户
     * @return 操作结果
     */
    @Override
    @Transactional
    public Wrapper<Void> delete(CommonIdRequest request, UserLoginCacheDTO user) {
        ContentImage contentImage = contentImageRepository.findById(request.getId()).orElse(null);
        if (contentImage == null) {
            throw new BusinessException(ResponseCode.MAN_RECORDS_DON_T_EXIST);
        }
        if (contentImage.getStatus().equals(EnableDisableStatus.ENABLE.getCode())) {
            throw new BusinessException(ResponseCode.MAN_DATA_STATUS_INCORRECT_OPERATE_INVALID);
        }
        contentImageRepository.delete(contentImage);
        return Wrapper.success();
    }

    /**
     * 根据使用场景和所在位置获取所有
     * @param useScene 使用场景
     * @param position 所在位置
     * @return 操作结果
     */
    @Override
    public Wrapper<List<ContentImage>> findAllByUseSceneAndPosition(Integer useScene, Integer position) {
        List<ContentImage> list = contentImageRepository.findAllByUseSceneAndPositionAndStatus(useScene, position, CommonBooleanEnum.YES.getCode());
        return Wrapper.success(list);
    }

    /**
     * 启动页、引导页
     * @return 操作结果
     */
    @Override
    public Wrapper<StartAndGuideResponse> startAndGuide() {
        StartAndGuideResponse response = new StartAndGuideResponse();

        List<ContentImage> guides = contentImageRepository.findAllByUseSceneAndPositionAndStatus(2, 3, CommonBooleanEnum.YES.getCode());
        List<ContentImage> starts = contentImageRepository.findAllByUseSceneAndPositionAndStatus(2, 4, CommonBooleanEnum.YES.getCode());

        response.setGuideUrlList(CollectionUtil.isNotEmpty(guides) ? guides.stream().map(ContentImage::getImageUrl).collect(Collectors.toList()) : new ArrayList<>());
        response.setStartUrl(CollectionUtil.isNotEmpty(starts) ? starts.get(0).getImageUrl() : null);

        return Wrapper.success(response);
    }
}
